//
// Created on 2024/7/31.
//
// Node APIs are not fully supported. To solve the compilation error of the interface cannot be found,
// please include "napi/native_api.h".

#ifndef ARKUI_C_API_ARKUIBASENODE_H
#define ARKUI_C_API_ARKUIBASENODE_H

#include "src/NativeModule.h"
#include <arkui/native_node.h>
#include <arkui/native_type.h>
#include <cstdint>
#include <list>

namespace NativeModule {

class ArkUIBaseNode {
    std::list<std::shared_ptr<ArkUIBaseNode>> children_;

protected:
    ArkUI_NodeHandle handle_;
    ArkUI_NativeNodeAPI_1 *nativeModule_ = nullptr;

    virtual void OnAddChild(const std::shared_ptr<ArkUIBaseNode> &child) {}
    virtual void OnRemoveChild(const std::shared_ptr<ArkUIBaseNode> &child) {}
    virtual void OnInsertChild(const std::shared_ptr<ArkUIBaseNode> &child, int32_t index) {}

public:
    explicit ArkUIBaseNode(ArkUI_NodeHandle handle)
        : handle_(handle), nativeModule_(NativeModuleInstance::getInstance()->GetNativeNodeAPI()) {}

    virtual ~ArkUIBaseNode() {
        if (!children_.empty()) {
            for (const auto &child : children_) {
                nativeModule_->removeChild(handle_, child->handle_);
            }
            children_.clear();
        }
        nativeModule_->disposeNode(handle_);
    }

    ArkUI_NodeHandle GetHandle() const { return handle_; }

    void AddChild(const std::shared_ptr<ArkUIBaseNode> &child) {
        children_.emplace_back(child);
        OnAddChild(child);
    }

    void RemoveChild(const std::shared_ptr<ArkUIBaseNode> &child) {
        children_.remove(child);
        OnRemoveChild(child);
    }

    void InsertChild(const std::shared_ptr<ArkUIBaseNode> &child, int32_t index) {
        if (index >= children_.size()) {
            AddChild(child);
        } else {
            auto iter = children_.begin();
            std::advance(iter, index);
            children_.insert(iter, child);
            OnInsertChild(child, index);
        }
    }
};

} // namespace NativeModule

#endif // ARKUI_C_API_ARKUIBASENODE_H
